package com.invengo.module_check.ui.activity.main;

import android.app.Application;

import androidx.annotation.NonNull;

import com.invengo.library_rfid.device.ConnectImpl;
import com.invengo.library_rfid.device.ConnectState;
import com.invengo.library_rfid.device.IConnect;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.cache.ACache;
import me.goldze.mvvmhabit.utils.cache.AKey;

/**
 * @author buoker
 * @version 1.0.0
 * @date 2023/10/24
 * @className java.lang.String
 */
public class MainViewMode extends BaseViewModel {
    public SingleLiveEvent<Boolean> showConnectState = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> connectState = new SingleLiveEvent<>();

    private int retryCount = 0;

    private boolean isConnect = false;

    public MainViewMode(@NonNull Application application) {
        super(application);
        showConnectState.postValue(ACache.getInstance().getAsBoolean(AKey.SHOW_DEVICE_CONNECT_STATE));
        RxBus.getDefault().toObservable(Boolean.class).subscribe(aBoolean -> {
            retryCount++;
            isConnect = aBoolean;
            connectState.postValue(aBoolean);
        });
        RxBus.getDefault().toObservable(ConnectState.class).subscribe(connectState -> {
            showConnectState.postValue(connectState == ConnectState.SHOW);
        });
    }

    private IConnect connect = new ConnectImpl();

    public BindingCommand reConnectCommand = new BindingCommand(() -> {
        if (retryCount >= (isConnect ? 5 : 2)) {
            retryCount = 0;
            connect.reConnect();
            ToastUtils.showShort("尝试执行重连操作。。。");
        } else {
            ToastUtils.showShort("请不要频繁使用重连操作。。。");
        }
    });
}
